package org.subject.utils;

import org.apache.poi.hssf.usermodel.*;
import org.subject.entity.User;

import java.util.List;

/**
 * Created by kai on 2017/5/7.
 */
public class ExcelUtil {
    /**
     * @param userList
     * @return HSSFWorkbook    返回类型
     * @throws
     * @Title: generateWorkbook
     * @Description: 根据条件生成excel文本对象
     */
    public static HSSFWorkbook generateWorkbook(List<User> userList) {
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("报名表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("序号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("学号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);
        /*cell = row.createCell((short) 3);
        cell.setCellValue("生日");
        cell.setCellStyle(style);*/


        for (int i = 0; i < userList.size(); i++) {
            row = sheet.createRow((int) i + 1);
            User user = (User) userList.get(i);
            // 第四步，创建单元格，并设置值
            cell = row.createCell((short) 0);
            cell.setCellValue((int) (i + 1));
            cell.setCellStyle(style);
            cell = row.createCell((short) 1);
            cell.setCellValue(user.getUserNumber());
            cell.setCellStyle(style);
            cell = row.createCell((short) 2);
            cell.setCellValue(user.getUserName());
            cell.setCellStyle(style);
            /*cell = row.createCell((short) 3);
            cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
                    .getBirth()));*/
        }

        return wb;
    }

}
